package com.example.moonshine.redzxingtree.Fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.moonshine.redzxingtree.Activity.SuccessActivity;
import com.example.moonshine.redzxingtree.Data.PostlistData;
import com.example.moonshine.redzxingtree.Data.SidSelectData;
import com.example.moonshine.redzxingtree.Data.findWarehouseListData;
import com.example.moonshine.redzxingtree.Helper.DataDBHepler;
import com.example.moonshine.redzxingtree.R;
import com.example.moonshine.redzxingtree.Util.SavePamasInfo;
import com.example.moonshine.redzxingtree.Util.SpostHttpMap;
import com.example.moonshine.redzxingtree.Util.SureDialog;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by moonshine on 2018/2/4.
 */

public class FirstFragment extends Fragment {

    private View view;

    private static final String TAG = "MainActivity";

    DataDBHepler dbHepler;
    ArrayList postlist = new ArrayList();
    ListView listView;
    PostAdapter postAdapter;
    String AluminumCode =null;
    String orderId=null;
    String targetList=null;
    String sysIds=null;
    static String matchingAluminumCode=null;
    static String matchTargetlist=null;
    static String matchOrderId=null;
    String[]      sysIdPotion    =new String[]{};
    String[]      sysname        =new String[]{};
    String        sysId          =null;
    SavePamasInfo mSavePamasInfo = new SavePamasInfo();
    private static final int REQUEST_CODE = 1;

    /**
     * fragment的视图
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ZXingLibrary.initDisplayOpinion(getActivity());
        view = inflater.inflate(R.layout.fg1, container, false);
        dbHepler = new DataDBHepler(getContext());
        if (dbHepler.isIdorSid())
        {
            ArrayList<SidSelectData> DataList = dbHepler.FindSidData();
            final SidSelectData data = new SidSelectData(DataList.get(0).getId(),DataList.get(0).getId(),DataList.get(0).getSysids());
            sysIds = data.getSysids();
            Log.i(TAG,"sysids:"+sysIds);
            sysIdPotion = sysIds.replace("[","").replace("]","").split(",");
            Log.i(TAG,"sysIdPotion:"+sysIdPotion[0]);
        }
        sysname = mSavePamasInfo.getInfo(getContext(),"sysname","login").split(",");
        initSpinner();
        final RefreshLayout refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshlayout) {
                try {
                    init();
                    Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishRefresh(true/*,false*/);//传入false表示刷新失败
                } catch (Exception e) {
                    e.printStackTrace();
                    refreshlayout.finishRefresh(false/*,false*/);//传入false表示刷新失败
                    Toast.makeText(getContext(), "刷新失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(true/*,false*/);//传入false表示加载失败
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
//        refreshLayout.setRefreshHeader(new BezierRadarHeader(this).setEnableHorizontalDrag(true));
//设置 Footer 为 球脉冲 样式
//        refreshLayout.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
//        Time();
        return view;
    }
    public void initSpinner() {
        final Spinner sp;
        sp = view.findViewById(R.id.TD_Spinner);
        final String[] list = new String[sysname.length];
        for (int i=0; i<sysname.length;i++)
        {
            String sting = sysname[i];
            list[i]=sting;
            Log.i(TAG, "数据为"+sting);
        }
        //第二步：为下拉列表定义一个适配器，这里就用到里前面定义的list。
        final ArrayAdapter<String> listadapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_text, list);
        //为适配器设置下拉列表下拉时的菜单样式。
        listadapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
        //将适配器添加到下拉列表上
        sp.setAdapter(listadapter);
        //为下拉列表控框定义点击，这个时间相应，菜单被点中
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView)view;
                tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
                Log.i(TAG, "位置" + position);
                StringBuffer sb = new StringBuffer();
                if (position==0)
                {
                    for (int i = 0; i < sysIdPotion.length; i++) {
                        sb.append(sysIdPotion[i]);
                        if (i<sysIdPotion.length-1) {
                            sb.append(",");
                        }
                    }
                    sysId = sb.toString();
                }else
                {
                    sysId = sb.append(sysIdPotion[position-1]).toString();
                }
                listadapter.notifyDataSetChanged();
                postlist.clear();
                initView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    private void initView() {
        listView = view.findViewById(R.id.list_view);
        new Thread(new Runnable() {
            @Override
            public void run() {
                new AnotherTask().execute("");
            }
        }).start();
        postAdapter = new PostAdapter(getContext(), postlist);
        listView.setAdapter(postAdapter);

    }

    public void init(){
        postlist.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                new AnotherTask().execute("");
            }
        }).start();
    }

    private class AnotherTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPostExecute(String result) {
            //对UI组件的更新操作
            Gson gson = new Gson();
            try {
                PostlistData postlistData = gson.fromJson(result,PostlistData.class);
                List<findWarehouseListData> listData = postlistData.getValues();
                if (listData.size()==0) {
                    Toast.makeText(getActivity(),"数据为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                for(int i = 0;i<listData.size();i++)
                {
                    String id = listData.get(i).getTargetList();
                    String num = listData.get(i).getAluminumCode();
                    String time = listData.get(i).getWarehousingInDate().substring(0,10);
                    String oid = listData.get(i).getOrderId();
                    findWarehouseListData p = new findWarehouseListData(id,num,time,oid);
                    postlist.add(p);
                }
                try{
                    postAdapter.notifyDataSetChanged();
                }catch (Exception e){
                    Log.e(TAG, "postlisthttp: ",e );
                    Toast.makeText(getActivity(), "服务器异常", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        protected String doInBackground(String... params) {
            //耗时的操作
            String findWarehouseUrl = "http://119.23.219.22:80/element-plc/find-finished-warehouse";
            if (sysId.equals(""))
            {
                sysId="sysids";
            }
            Gson gson =new Gson();
            OkHttpClient client = new OkHttpClient();
             MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            Log.i("tag","sysIds:"+sysIds);
            FormBody body = new FormBody.Builder()
                    .add("sysIds",sysIds.replace("[","").replace("]",""))
                    .build();
            Request request = new Request.Builder()
                    .url(findWarehouseUrl)
                    .post(body)
                    .build();
            String result ="";
            try {
                Response response = client.newCall(request).execute();
                //获取后台传输的额status状态码
                result = response.body().string();

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground: ",e );
            }
            return result;
        }
    }

    public class PostAdapter extends BaseAdapter {

        private ArrayList<findWarehouseListData> List;
        private Context context;

        PostAdapter(Context context, ArrayList<findWarehouseListData> list) {
            this.context = context;
            this.List = list;
        }

        @Override
        public int getCount() {
            return List.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = view.inflate(context, R.layout.activity_set_item, null);
            }

            TextView tv = view.findViewById(R.id.set_item_id);
            TextView tv1 = view.findViewById(R.id.set_item_name);
            TextView tv2 = view.findViewById(R.id.set_item_time);

            final findWarehouseListData data = List.get(position);
            tv.setText(data.getTargetList());
            tv1.setText(data.getAluminumCode());
            tv2.setText(data.getWarehousingInDate().substring(0,9));
            Button button1 =view.findViewById(R.id.fg1_saoma);
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    matchingAluminumCode = data.getAluminumCode();
                    matchOrderId = data.getOrderId();
                    matchTargetlist = data.getTargetList();
                    Intent intent = new Intent(getActivity(), CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            });
            return view;
        }
    }

    public void showDialog() {
        final SureDialog Dialog = new SureDialog(getActivity());
        Dialog.setTitle("消息提示");
        Dialog.setMessage("扫描成功，是否确认出库?");
        Dialog.setYesOnclickListener("确定", new SureDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        SpostHttpMap spostHttpMap = new SpostHttpMap();

                        /**
                         * 截取扫描的结果订单号
                         */
                         String OutWarehouseUrl ="http://119.23.219.22:80/element-plc/add-warehouse-out";

                        String OutWarehouseResult = spostHttpMap.posthttpmap(targetList,orderId,AluminumCode,OutWarehouseUrl);
                        Log.i(TAG,"结果为："+OutWarehouseResult);
                        try {
                            if (OutWarehouseResult.equals("10")) {
                                Toast.makeText(getActivity(), "出库成功", Toast.LENGTH_LONG).show();
                                init();
                                postlist.clear();
                                if (dbHepler.isIdorOid()) {
                                    dbHepler.updateoid(orderId);
                                } else {
                                    dbHepler.addoid("1", orderId);
                                }
                                Intent intent1 = new Intent();
                                intent1.setClass(getActivity(), SuccessActivity.class);
                                startActivity(intent1);
                            } else if (OutWarehouseResult.equals("12")) {
                                Toast.makeText(getActivity(), "出库失败，网络错误", Toast.LENGTH_LONG).show();
                            }else {
                                Toast.makeText(getActivity(), "出库失败，网络错误", Toast.LENGTH_LONG).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "网络开小差啦", Toast.LENGTH_LONG).show();
                        }
                        Looper.loop();
                    }
                }).start();
                Dialog.dismiss();
            }
        });
        Dialog.setNoOnclickListener("取消", new SureDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
//                Intent intent = new Intent();
//                intent.putExtra("index", "0");
//                intent.setClass(getActivity(), MainActivity.class);
//                startActivity(intent);
                Dialog.dismiss();
            }
        });
        Dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Log.i("tag","结果："+result);
                    if (result!=null){
                        String str[] = result.split("/");
                        orderId = str[str.length-1];
                        Log.i("tag","orderId："+orderId);
                        targetList = str[str.length-4];
                        AluminumCode =str[str.length-3];
                        Log.i("tag","参数为：matchingAluminumCode："+matchingAluminumCode+",AluminumCode："+AluminumCode+",matchTargetlist："+targetList+",matchOrderId："+matchOrderId+",orderId:"+orderId);
                        if (matchingAluminumCode.equals(AluminumCode)&&matchTargetlist.equals(targetList)&&matchOrderId.equals(orderId))
                        {
                            showDialog();
                        }else {
                            Toast.makeText(getActivity(), "订单号不匹配", Toast.LENGTH_SHORT).show();
                        }

                    }
                    Log.i("tag","结果："+result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getActivity(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}